﻿using System;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class ModalContactDetailControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!Page.IsPostBack)
            {
                SetControlEnabledState(false);
                if (Request.QueryString["action"] == "add")
                {
                    SetAddNewAction();
                }
            }
        }
        private void SetAddNewAction()
        {
            btnEditContact.Visible = false;
            btnSaveContact.Visible = true;
            btnDeleteContact.Visible = false;
        }
        public void SetControlEnabledState(bool bstate = false)
        {
            
            RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelContactDetail.ContentTemplateContainer, bstate);
        }
        protected void btnEditContact_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                SetControlEnabledState(true);
                btnEditContact.Visible = false;
                btnSaveContact.Visible = true;
                btnDeleteContact.Visible = true;
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                btnEditContact.Visible = false;
                btnSaveContact.Visible = false;
                btnDeleteContact.Visible = false;
            }
        }
        protected void btnModalOK_Click(object sender, EventArgs e)
        {
            mpeModalContactDetail.Hide();
            var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
            nameValues.Set("tabindex", "1");
            string url = Request.Url.AbsolutePath;
            string updatedQueryString = "?" + nameValues.ToString();
            Response.Redirect(url + updatedQueryString);

        }
        protected void btnDeleteContact_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int companyid = userIdentity.RSCompanyId;
                int contactid = txtContactId.Text == "" ? 0 : Convert.ToInt32(txtContactId.Text);

                if (companyid > 0 && contactid > 0)
                {
                    SqlCommand sqlCmd = new SqlCommand();
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@contactid", SqlDbType.Int, 0, ParameterDirection.Input, contactid);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
                    SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblContact WHERE ContactId=@contactid AND CompanyId=@companyid");
                    SQLHelper.ExecuteScalarCmd(sqlCmd);
                    int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                    lblMessage.Text = "Contact Deleted Successfully!";
                    lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                }
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
            }
            btnEditContact.Visible = false;
            btnSaveContact.Visible = false;
            btnDeleteContact.Visible = false;
            SetControlEnabledState(false);
        }
        protected void btnSaveContact_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                int CompanyId = userIdentity.RSCompanyId;
                int BillingLocationId = ddlBillingLocationId.SelectedValue == "0" ? 0 : Convert.ToInt32(ddlBillingLocationId.SelectedValue);
                int ContactId = txtContactId.Text == "" ? 0 : Convert.ToInt32(txtContactId.Text);
                string FirstName = txtFirstName.Text.Trim();
                string MiddleName = txtMiddleName.Text.Trim();
                string LastName = txtLastName.Text.Trim();
                string Phone = txtPhone.Text.Trim();
                string Mobile = txtMobile.Text.Trim();
                string Fax = txtFax.Text.Trim();
                string Email = txtEmail.Text.Trim();
                string Title = txtTitle.Text.Trim();
                string Note = txtContactNote.Text.Trim();

                SqlCommand sqlCmd = new SqlCommand();

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@FirstName", SqlDbType.NVarChar, 25, ParameterDirection.Input, FirstName);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@MiddleName", SqlDbType.NVarChar, 25, ParameterDirection.Input, MiddleName);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LastName", SqlDbType.NVarChar, 25, ParameterDirection.Input, LastName);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Phone", SqlDbType.NVarChar, 15, ParameterDirection.Input, Phone);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Mobile", SqlDbType.NVarChar, 15, ParameterDirection.Input, Mobile);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Fax", SqlDbType.NVarChar, 15, ParameterDirection.Input, Fax);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Email", SqlDbType.NVarChar, 50, ParameterDirection.Input, Email);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Title", SqlDbType.NVarChar, 25, ParameterDirection.Input, Title);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Note", SqlDbType.NVarChar, -1, ParameterDirection.Input, Note);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Active", SqlDbType.Bit, 0, ParameterDirection.Input, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@BillingLocationId", SqlDbType.Int, 0, ParameterDirection.Input, BillingLocationId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ContactId", SqlDbType.Int, 0, ParameterDirection.Input, ContactId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveContact");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                lblMessage.Text = "Contact Successfully Saved!";
                lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                hfRedirectURL.Value = Request.RawUrl;
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
            }
            btnEditContact.Visible = false;
            btnSaveContact.Visible = false;
            btnDeleteContact.Visible = false;
            SetControlEnabledState(false);
        }

        public void ShowModal(int companyid, int contactid)
        {
            hfRedirectURL.Value = "";
            lblMessage.Text = "Contact";

            if (LoadContactData(companyid, contactid))
            {
                btnEditContact.Visible = true;
                btnSaveContact.Visible = false;
                btnDeleteContact.Visible = false;
                SetControlEnabledState(false);
            }
            else
            {
                btnEditContact.Visible = false;
                btnSaveContact.Visible = true;
                btnDeleteContact.Visible = false;
                SetControlEnabledState(true);
            }
            mpeModalContactDetail.Show();
        }

        public bool LoadContactData(int companyid, int contactid)
        {
            bool bHasValue = false;
            if (contactid > 0)
            {
                LoadContactBillingLocationID(companyid, contactid);

                String strSQL = "select FirstName,MiddleName,LastName,BillingLocationId,Phone,Mobile,Fax,Email,Title,Note,CompanyId,Active from rs_tblContact where contactid=@contactid and companyid=@companyid";
                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                myCommand = new SqlCommand(strSQL, myConnection);
                SqlDataReader myDataReader;

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@contactid";
                param.Value = contactid;
                myCommand.Parameters.Add(param);

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@companyid";
                param.Value = companyid;
                myCommand.Parameters.Add(param);

                myConnection.Open();
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                if (myDataReader.HasRows)
                {
                    myDataReader.Read();
                    txtContactId.Text = contactid.ToString();
                    txtFirstName.Text = myDataReader["FirstName"].ToString();
                    txtMiddleName.Text = myDataReader["MiddleName"].ToString();
                    txtLastName.Text = myDataReader["LastName"].ToString();
                    txtPhone.Text = myDataReader["Phone"].ToString();
                    txtMobile.Text = myDataReader["Mobile"].ToString();
                    txtFax.Text = myDataReader["Fax"].ToString();
                    txtEmail.Text = myDataReader["Email"].ToString();
                    txtTitle.Text = myDataReader["Title"].ToString();
                    txtContactNote.Text = myDataReader["Note"].ToString();

                    if (myDataReader["BillingLocationID"] != DBNull.Value)
                        if (ddlBillingLocationId.Items.FindByValue(myDataReader["BillingLocationID"].ToString()) != null)
                            ddlBillingLocationId.SelectedValue = myDataReader["BillingLocationID"].ToString();

                    bHasValue = true;
                }

                myConnection.Close();
            }
            return bHasValue;
        }

        private void LoadContactBillingLocationID(int companyid, int contactid)
        {
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "SELECT LocationID FROM [rs_tblContactLocation] WHERE ContactID=@ContactID AND CompanyID=@CompanyID ORDER BY LocationID";
            SqlParameter param;
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);
            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@contactid";
            param.Value = contactid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            ddlBillingLocationId.Items.Clear();
            ddlBillingLocationId.DataSource = myDataReader;
            ddlBillingLocationId.DataTextField = "LocationID";
            ddlBillingLocationId.DataValueField = "LocationID";
            ddlBillingLocationId.DataBind();
            ddlBillingLocationId.Items.Insert(0, new ListItem("< Please select >", "0"));
            myConnection.Close();
        }

    }
}